import { mapActions, mapGetters } from 'vuex'
import { addCss, removeAllCss, themeList, getReadTimeByMinute } from './book'
import { getBookmark, saveLocation, getBookShelf, saveBookShelf } from './localStorage'
import { gotoBookDetail, appendAddToShelf, computeId, removeAddFromShelf } from './store'
import { shelf } from '../api/store'

export const storeShelfMixin = {
  computed: {
    ...mapGetters([
      'isEditMode',
      'shelfList',
      'shelfSelected',
      'shelfTitleVisible',
      'offsetY',
      'shelfCategory',
      'currentType'
    ])
  },
  methods: {
    ...mapActions([
      'setIsEditMode',
      'setShelfList',
      'setShelfSelected',
      'setShelfTitleVisible',
      'setOffsetY',
      'setShelfCategory',
      'setCurrentType'
    ]),
    showBookDetail(book) {
      gotoBookDetail(this, book)
    },
    getCategoryList(title) {
      this.getShelfList().then(() => {
        const categoryList = this.shelfList.filter(book => book.type === 2 && book.title === title)[0]
        this.setShelfCategory(categoryList)
      })
    },
    getShelfList() {
			// 从localStorage中获取读书信息
			let shelfList = getBookShelf()
			if (!shelfList) {
				shelf().then(response => {
					if (response.status === 200 && response.data && response.data.bookList) {
						shelfList = appendAddToShelf(response.data.bookList)
						// 将设置存入localStroge中
						saveBookShelf(shelfList)
						// 将设置存入Vuex中
						return this.setShelfList(shelfList)
					}
				})
			} else {
				return this.setShelfList(shelfList)
			}
		},
    moveOutOfGroup(f) {
      this.setShelfList(this.shelfList.map(book => {
        if (book.type === 2 && book.itemList) {
          book.itemList = book.itemList.filter(subBook => !subBook.selected)
        }
        return book
      })).then(() => {
        // let list = removeAddFromShelf(this.shelfList)
        // list = [].concat(list, ...this.shelfSelected)
        // list = appendAddToShelf(list)
        // list = computeId(list)
        const list = computeId(appendAddToShelf([].concat(removeAddFromShelf(this.shelfList), ...this.shelfSelected)))
        this.setShelfList(list).then(() => {
          this.simpleToast(this.$t('shelf.moveBookOutSuccess'))
          // 保存数据
          if (f) f()
        })
      })
    }
  }
}

export const storeHomeMixin = {
  computed: {
    ...mapGetters(['offsetY', 'hotSearchOffsetY', 'flapCardVisible'])
  },
  methods: {
    ...mapActions(['setOffsetY', 'setHotSearchOffsetY', 'setFlapCardVisible']),
    showBookDetail(book) {
      gotoBookDetail(this, book)
    }
  }
}

export const ebookMixin = {
	computed: {
		...mapGetters([
      'fileName',
      'menuVisible',
      'settingVisible',
      'defaultFontSize',
      'defaultFontFamily',
      'fontFamilyVisible',
      'defaultTheme',
      'bookAvailable',
      'progress',
      'section',
      'isPaginating',
      'currentBook',
      'navigation',
      'cover',
      'metadata',
      'paginate',
      'pagelist',
      'offsetY',
      'isBookmark'
    ]),
    themeList() {
			return themeList(this)
		},
    getSectionName() { // 获取章节的标题
			// if (this.section) {
			// 	const sectionInfo = this.currentBook.section(this.section)
			// 	if (sectionInfo && sectionInfo.href && this.currentBook && this.currentBook.navigation) {
			// 		return this.currentBook.navigation.get(sectionInfo.href).label
			// 	}
			// }
			// return ''
			// 采用处理后的一维数组渲染章节标题
			return this.section ? this.navigation[this.section].label : ''
		}
	},
	methods: {
		...mapActions([
      'setFileName',
      'setMenuVisible',
      'setSettingVisible',
      'setDefaultFontSize',
      'setDefaultFontFamily',
      'setFontFamilyVisible',
      'setDefaultTheme',
      'setBookAvailable',
      'setProgress',
      'setSection',
      'setIsPaginating',
      'setCurrentBook',
      'setNavigation',
      'setCover',
      'setMetadata',
      'setPaginate',
      'setPagelist',
      'setOffsetY',
      'setIsBookmark'
    ]),
    initGlobalStyle() { // 设置全局样式
      removeAllCss() // 移除之前的样式
			switch (this.defaultTheme) {
				case 'Default':
					addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_default.css`)
					break
				case 'Eye':
					addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_eye.css`)
					break
				case 'Gold': 
					addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_gold.css`)
					break
				case 'Night':
					addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_night.css`)
					break
				default: // 默认组题
					addCss(`${process.env.VUE_APP_RES_URL}/theme/theme_default.css`)
					break
			}
			// addCss('http://127.0.0.1:8081/theme/theme_default.css')
		},
    refreshLocation() { // 刷新进度条的位置
			const currentLocation = this.currentBook.rendition.currentLocation()
      if (currentLocation && currentLocation.start) {
        const startCfi = currentLocation.start.cfi
			  // 获取当前的进度
			  const progress = this.currentBook.locations.percentageFromCfi(startCfi)
			  this.setProgress(Math.floor(progress * 100))
        // 刷新进度条下的标题
        this.setSection(currentLocation.start.index)
			  // 保存进度到缓存中 
			  saveLocation(this.fileName, startCfi)
        const bookmark = getBookmark(this.fileName)
        if (bookmark) { // 判断当前页初始是否为书签页
          if (bookmark.some(item => item.cfi === startCfi)) {
            this.setIsBookmark(true)
          } else {
            this.setIsBookmark(false)
          }
        } else {
          this.setIsBookmark(false)
        }
        if (this.pagelist) { // 判断分页是否完成
          const totalPage = this.pagelist.length
          const currentPage = currentLocation.start.location
          if (currentPage && currentPage > 0) {
            this.setPaginate(currentPage + ' / ' + totalPage)
          } else {
            this.setPaginate('')
          }
        } else {
          this.setPaginate('')
        }
      }
		},
    display(target, cb) { // 封装display方法
			if (target) {
				this.currentBook.rendition.display(target).then(() => {
          this.refreshLocation()
          if (cb) cb()
        })
			} else {
				this.currentBook.rendition.display().then(() => {
          this.refreshLocation()
          if (cb) cb()
        })
			}
		},
    hideTitleAndMenu() {
			// 翻页菜单栏的显示与隐藏
			// this.$store.dispatch('setMenuVisible', false)
			this.setMenuVisible(false)
			// 翻页时， 隐藏字体设置菜单栏
			this.setSettingVisible(-1)
			// 翻页隐藏字体设置菜单栏
			this.setFontFamilyVisible(false)
		},
    getReadTimeText() {
			// 渲染阅读时间
			return this.$t('book.haveRead').replace('$1', getReadTimeByMinute(this.fileName))
		},
	}
}
